package org.onionframework.persistence.util;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.MappedSuperclass;

import org.onionframework.persistence.model.Model;
import org.onionframework.persistence.model.annotation.DomainModel;
import org.onionframework.persistence.model.logic.Named;
import org.springframework.util.Assert;

/**
 * 模型相关的工具类
 * 
 * @author allan
 *
 */
public class ModelUtils {

	public static String getFullName(Model<? extends Serializable> model){
		Assert.notNull(model);
		
		DomainModel domainModel = model.getClass().getAnnotation(DomainModel.class);
		
		StringBuilder result = new StringBuilder();
		
		if(domainModel != null)
			result.append(domainModel.name()).append('#');
		else
			result.append(model.getClass().getSimpleName()).append('#');
		
		if(model instanceof Named)
			result.append(((Named)model).getName());
		else
			result.append(model.getId());
		
		return result.toString();
	}
	
	public static String getTypeName(Object model){
		Assert.notNull(model);
		
		DomainModel domainModel = model.getClass().getAnnotation(DomainModel.class);
		
		if(domainModel != null)
			return domainModel.name();
		else
			return model.getClass().getSimpleName();
		
	}
	
	 /**
     * 根据一个标记了@Entity的实体类，找到其上层的类
     * @param clazz
     * @return
     */
	public static Class<?> getRootEntityClass(Class<?> clazz) {
		
		if(!clazz.isAnnotationPresent(Entity.class))
			return clazz;
		
		Class<?> superClass = clazz.getSuperclass();
		
		while(!superClass.equals(Object.class)){
			if(superClass.isAnnotationPresent(Entity.class)
				|| superClass.isAnnotationPresent(MappedSuperclass.class))
			{
				superClass = superClass.getSuperclass();
				continue;
			}
			else
				break;
		}
		return superClass;
	}
	
}
